package cn.itcast.controller.factory;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.domain.company.Company;
import cn.itcast.service.cargo.FactoryService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/factory")
public class FactoryController extends BaseController {


    @Reference
    private FactoryService factoryService;


    @RequestMapping(value = "/list",name = "展示厂家列表数据")
    public String findAll(@RequestParam(name="page",defaultValue = "1") Integer pageNum,
                          @RequestParam(name="pageSize",defaultValue = "10") Integer pageSize){
        PageInfo<Factory> pageInfo = factoryService.findPage(pageNum,pageSize);
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值

//        List<Factory> factoryList = factoryService.findAllFactory();
//        request.setAttribute("factoryList",factoryList);
        return "factory/factory-list";
    }

    @RequestMapping(value = "/delete",name = "删除厂家列表数据")
    public String delete(String id) {
        factoryService.delete(id);
        return "redirect:/factory/list.do";
    }

    @RequestMapping(value = "/toAdd",name = "进入到新增厂家页面")
    public String toAdd(String id) {
        List<Factory> factoryList = factoryService.findAllFactory();
        request.setAttribute("factoryList",factoryList);
        return "factory/factory-add";
    }

    @RequestMapping(value = "/edit",name = "保存厂家信息")
    public String edit(Factory factory) {
        if(StringUtils.isEmpty(factory.getId())){
            factory.setId(UUID.randomUUID().toString());
            factory.setCreateTime(new Date());
            factory.setUpdateTime(new Date());
            factoryService.save(factory);
        }else{
            factoryService.update(factory);
        }
        return "redirect:/factory/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "修改厂家信息")
    public String toUpdate(String id) {
        Factory factory = factoryService.findById(id);
        request.setAttribute("factory",factory);

        List<Factory> factoryList = factoryService.findAllFactory();
        request.setAttribute("factoryList",factoryList);
        return "factory/factory-update";
    }
}
